package com.skywolf.chem.usercenterapi;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.skywolf.chem.article.mapper.ArticleMapper;
import com.skywolf.chem.article.service.IArticleService;
import com.skywolf.chem.common.enums.ResponseCodeEnum;
import com.skywolf.chem.common.sysconfig.response.RespData;
import com.skywolf.chem.riding.entity.Info;
import com.skywolf.chem.riding.service.IInfoService;
import com.skywolf.chem.usercenterapi.entity.CustomerInfo;
import com.skywolf.chem.usercenterapi.pojo.LoginParam;
import com.skywolf.chem.usercenterapi.pojo.WechatLoginParam;
import com.skywolf.chem.usercenterapi.service.ICustomerInfoService;
import com.skywolf.chem.utils.*;
import com.skywolf.chem.utils.sms.SendSms;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;

/**
 * <p>
 * app端用户表 前端控制器
 * </p>
 *
 * @author 
 * @since 2020-06-09
 */
@Slf4j
@RestController
@Api(value = "用户相关-用户端", description = "用户相关-用户端")
@RequestMapping("/ct/user/login-info")
public class LoginInfoController {

    @Autowired
    private IArticleService articleService;

    @Autowired
    private ICustomerInfoService customerInfoService;

    @Autowired
    IInfoService ridingService;

    @ApiOperation(value = "手机注册，发送短信",notes = "手机注册，发送短信")
    @RequestMapping(value = "/registerMsg",method = {RequestMethod.GET,RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<String> registerMsg(@RequestParam(value = "",required = true) String phone) {
        log.info("customer-info注册短信：{}", phone);
        if(!PhoneUtils.phoneCheck(phone)){
            return RespData.failure(ResponseCodeEnum.PHONE_ERROR);
        }
        QueryWrapper<CustomerInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CustomerInfo::getBindPhone, phone);
        CustomerInfo cus = customerInfoService.getOne(queryWrapper);
        if(cus!=null && cus.getPhoneStatus().equals(1)){
            return RespData.failure(ResponseCodeEnum.PHONE_DUPLICATE);
        }
        String code = PhoneUtils.getCode();
        SendSms.sendMsg(phone, code);
        CustomerInfo info = new CustomerInfo();
        info.setBindPhone(phone);
        info.setCodeTime(LocalDateTime.now());
        info.setMscCode(code);
        info.setUserName(phone);
        info.setNickName("chuanti"+code);
        if(cus!=null){
            info.setId(cus.getId());
            customerInfoService.updateById(info);
        }else{
            customerInfoService.save(info);
        }
        return RespData.success();
    }

    @ApiOperation(value = "用户手机号注册,且验证注册短信",notes = "用户手机号注册,且验证注册短信")
    @RequestMapping(value = "/registerPhone",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<String> registerPhone(@RequestBody LoginParam param) {
        QueryWrapper<CustomerInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CustomerInfo::getBindPhone, param.getUsername());
        CustomerInfo cus = customerInfoService.getOne(queryWrapper);
        if(cus!=null && cus.getPhoneStatus().equals(1)){
            return RespData.failure(ResponseCodeEnum.PHONE_DUPLICATE);
        }
        Long nowTime = System.currentTimeMillis()/1000;
        Long codeTime = cus.getCodeTime().toEpochSecond(ZoneOffset.of("+8"));
        if(nowTime-codeTime>300){
            return RespData.failure(ResponseCodeEnum.CODE_EXPIRE);
        }
        if(!param.getMacCode().equals(cus.getMscCode())){
            return RespData.failure(ResponseCodeEnum.CODE_ERROR);
        }
        if(StringUtils.isNotBlank(param.getPassword())){
            cus.setUserPwd(CryptUtil.EncoderByMd5(param.getPassword()));
        }
        cus.setPhoneStatus(1);
        cus.setHeadImg("https://chuanti-bucket.oss-cn-chengdu.aliyuncs.com/img/chuanti_head_img.png");
        customerInfoService.updateById(cus);
        return RespData.success();
    }


    @ApiOperation(value = "手机登录,发送短信",notes = "手机登录,发送短信")
    @RequestMapping(value = "/loginMsg",method = {RequestMethod.GET,RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<String> loginMsg(@RequestParam(value = "",required = true) String phone) {
        if(!PhoneUtils.phoneCheck(phone)){
            return RespData.failure(ResponseCodeEnum.PHONE_ERROR);
        }
        QueryWrapper<CustomerInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CustomerInfo::getBindPhone, phone);
        CustomerInfo cus = customerInfoService.getOne(queryWrapper);
        if(cus ==null || !cus.getPhoneStatus().equals(1)){
            return RespData.failure(ResponseCodeEnum.USER_NOT_FOUND);
        }
        String code = PhoneUtils.getCode();
        SendSms.sendMsg(phone, code);

        CustomerInfo info = new CustomerInfo();
        info.setCodeTime(LocalDateTime.now());
        info.setMscCode(code);
        info.setId(cus.getId());
        customerInfoService.updateById(info);
        log.info("loginPhone cus:{},info:{}", JSON.toJSONString(cus),JSON.toJSONString(info));
        return RespData.success();
    }

    @ApiOperation(value = "手机登录,验证短信",notes = "机登录,验证短信")
    @PostMapping("/loginPhone")
    public RespData<JSONObject> loginPhone(@RequestBody LoginParam param) {
        QueryWrapper<CustomerInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CustomerInfo::getBindPhone, param.getUsername());
        CustomerInfo cus = customerInfoService.getOne(queryWrapper);
        if(cus ==null || !cus.getPhoneStatus().equals(1)){
            return RespData.failure(ResponseCodeEnum.USER_NOT_FOUND);
        }
        Long nowTime = System.currentTimeMillis()/1000;
        Long codeTime = cus.getCodeTime().toEpochSecond(ZoneOffset.of("+8"));
        if(nowTime-codeTime>300){
            return RespData.failure(ResponseCodeEnum.CODE_EXPIRE);
        }
        if(!param.getMacCode().equals(cus.getMscCode())){
            log.info("loginPhone param:{},cus:{}", JSON.toJSONString(param),JSON.toJSONString(cus));
            return RespData.failure(ResponseCodeEnum.CODE_ERROR);
        }
        JSONObject token = customerInfoService.loginPhone(param);
        return RespData.success(token);
    }

    @ApiOperation(value = "用户名密码登录",notes = "用户名密码登录")
    @PostMapping("/loginAccountAndPwd")
    public RespData<JSONObject> loginAccountAndPwd(@RequestBody LoginParam param) {
        QueryWrapper<CustomerInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CustomerInfo::getUserName, param.getUsername());
        CustomerInfo user = customerInfoService.getOne(queryWrapper);
        if(user ==null || !user.getPhoneStatus().equals(1)){
            return RespData.failure(ResponseCodeEnum.USER_NOT_FOUND);
        }
        String pwd = CryptUtil.EncoderByMd5(param.getPassword());
        if(pwd.equals(user.getUserPwd())){
            String token = user.getId()+"|"+user.getUserName()+"|"+user.getUserPwd()+"|"+System.currentTimeMillis()/1000;
            String userToken = CryptUtil.IMDes3Encode(token, RequestConstans.decode_pwd);
            JSONObject obj = new JSONObject();
            obj.put("userToken",userToken);
            obj.put("userId",user.getId());
            return RespData.success(obj);
        }
        return RespData.failure(ResponseCodeEnum.USER_INVALID_USERNAME_PASSWORD);
    }


    @RequestMapping(value = "/wechatLogin",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    @ApiOperation(value = "微信登录接口",notes = "微信登录接口")
    public RespData<JSONObject> wechatLogin(HttpServletRequest request, HttpServletResponse response, @RequestBody WechatLoginParam login){
        if(StringUtils.isBlank(login.getWechatCode()) || login==null){
            return RespData.failure(ResponseCodeEnum.PARAM_ERROR);
        }
        String appid = SysConfig._this.getProperty("wechat.appid");
        String appsecret = SysConfig._this.getProperty("wechat.appsecret");
        //获取openid
        try{
            Map<String,String> paramsMap = new HashMap<>();
            paramsMap.put("appid",appid);
            paramsMap.put("secret",appsecret);
            paramsMap.put("code",login.getWechatCode());
            paramsMap.put("grant_type","authorization_code");
            String resp = HttpUtils.postMap("https://api.weixin.qq.com/sns/oauth2/access_token", paramsMap);
            if(StringUtils.isBlank(resp)){
                return RespData.failure(ResponseCodeEnum.WECHATLOGIN_ERROR);
            }
            JSONObject obj = JSONObject.parseObject(resp);
            String accessToken = obj.getString("access_token");
            if(StringUtils.isBlank(accessToken)){
                return RespData.failure(ResponseCodeEnum.WECHATLOGIN_TOKEN_ERROR);
            }
            String openid = obj.getString("openid");
            String nickName = "";
            String headImg = "";
            try{
                paramsMap = new HashMap<>();
                paramsMap.put("access_token",accessToken);
                paramsMap.put("openid",openid);
                paramsMap.put("lang","zh_CN");
                String resp_userinfo = HttpUtils.getMap("https://api.weixin.qq.com/sns/userinfo", paramsMap);
                JSONObject userInfo = JSONObject.parseObject(resp_userinfo);
                headImg = userInfo.getString("headimgurl");
                nickName = userInfo.getString("nickname");
            }catch (Exception e){
                log.error("LoginInfoController.wechatLogin userinfo error data:"+JSON.toJSONString(login)+",error:{}",e);
            }
            JSONObject user = customerInfoService.loginWechat(openid,headImg,nickName);
            return RespData.success(user);
        }catch (Exception e){
            log.error("LoginInfoController.wechatLogin data:"+JSON.toJSONString(login)+",error:{}",e);
            return RespData.failure(ResponseCodeEnum.WECHATLOGIN_FAIL_ERROR);
        }
    }


    @ApiOperation(value = "手机登录,验证短信",notes = "机登录,验证短信")
    @GetMapping("/yaoqian")
    public RespData<String> yaoqian(HttpServletRequest request,HttpServletResponse response) {
        String opt = request.getParameter("code");
        String msg = request.getParameter("msg");
        if(opt.startsWith("chuantibug-")){
            articleService.updateArticlebug(opt,msg);
        }
        return RespData.success();
    }

    public List<String> areaLit = Arrays.asList("成都市","自贡市","攀枝花市","泸州市","德阳市","绵阳市","广元市","遂宁市","内江市",
            "乐山市","南充市","宜宾市","广安市","达州市","巴中市","雅安市","眉山市","资阳市","阿坝州","甘孜州","凉山州");

    @ApiOperation(value = "手机登录,验证短信",notes = "机登录,验证短信")
    @GetMapping("/qxcreate")
    public RespData<String> qxcreate(HttpServletRequest request,HttpServletResponse response) {
        String num = request.getParameter("num");
        if(StringUtils.isNotBlank(num)){
            Integer addNum = Integer.valueOf(num);
            Long id = Long.valueOf("-"+ridingService.getMaxId());
            List<LocalDateTime> listTime = ridingService.getLocalDateTime();
            Random random = new Random();
            int value = random.nextInt(listTime.size());
            for (int i=0;i<addNum;){
                try{
                    String cardNo = TimeUtils.getIdNo(true);
                    String mobile = TimeUtils.getTelephone();
                    Long uid = id-i;
                    Double numLicheng = TimeUtils.getLiChen();
                    QueryWrapper<Info> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("card_no",cardNo);
                    queryWrapper.or(wrapper -> wrapper.eq("mobile", mobile));
                    Info info = ridingService.getOne(queryWrapper);
                    if(info==null){
                        Integer sex = 1;
                        if(i%30==0){
                            sex = 0;
                        }
                        String userName =TimeUtils.getChineseName(sex);
                        info = new Info();
                        info.setUid(uid);
                        info.setUserSex(sex);
                        info.setMobile(mobile);
                        info.setUserName(userName);
                        info.setCardNo(cardNo);
                        info.setNumTotal(numLicheng);

                        info.setCreatedTime(listTime.get(value));
                        info.setUpdatedTime(LocalDateTime.now());
                        info.setNmg(1);
                        int n = random.nextInt(areaLit.size());
                        String area = areaLit.get(n);
                        info.setCity(area);
                        ridingService.addRiding(info);
                        i++;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        return RespData.success();
    }

}
